package cn.edu.stu.oauth;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements OnCodeGetListener {

    TextView mTextView;
    WebView mWebView;

    EditText mUserNameEditText;
    EditText mPasswordEditText;
    Button mLoginButton;
    MyWebViewClient client;
    private boolean isFinishLoad;
    private Runnable timeOutRunnable;

    public static final int TIME_OUT = 10 * 1000;

    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mUserNameEditText = (EditText) findViewById(R.id.userNameEditText);
        mUserNameEditText.setText("13yjli3");
        mPasswordEditText = (EditText) findViewById(R.id.passwordEditText);
        mPasswordEditText.setText("O3oO3o");
        mLoginButton = (Button) findViewById(R.id.loginButton);
        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });

        mTextView = (TextView) findViewById(R.id.textView);
        mWebView = (WebView) findViewById(R.id.webView);

        mHandler = new Handler();

        client = new MyWebViewClient();
        client.setOnCodeGetListener(this);
        mWebView.setWebViewClient(client);
        mWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");

        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);

        mWebView.clearCache(true);
        CookieManager.getInstance().removeAllCookie();
    }

    private void login() {
        client.clearCode();
        isFinishLoad = false;
        mWebView.loadUrl("https://oauth.stu.edu.cn/oauth2/authorize?response_type=code&client_id=stusyllabus&redirect_uri=http://119.29.95.245:8080/oauth2_android");
        mLoginButton.setEnabled(false);
        timeOutRunnable = new Runnable() {
            @Override
            public void run() {
                if (!isFinishLoad) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            onTimeOut();
                        }
                    });
                }
            }
        };
        mHandler.postDelayed(timeOutRunnable, TIME_OUT);
    }


    @Override
    public void onCodeGet(String code) {
        Log.e("HTML", "onCodeGet");
        isFinishLoad = true;
        mWebView.clearCache(true);
        CookieManager.getInstance().removeAllCookie();
        mTextView.setText("你的code: " + code);
        mLoginButton.setEnabled(true);
        mHandler.removeCallbacks(timeOutRunnable);
    }

    @Override
    public void onCodeFail() {
        Log.e("HTML", "onCodeFail");
        mTextView.setText("账号或者密码错误");
        isFinishLoad = true;
        mWebView.stopLoading();
        mLoginButton.setEnabled(true);
        mHandler.removeCallbacks(timeOutRunnable);
    }

    @Override
    public void onTimeOut() {
        Log.e("HTML", "time out");
        mTextView.setText("Time Out");
        mWebView.stopLoading();
        isFinishLoad = true;
        mLoginButton.setEnabled(true);
        mHandler.removeCallbacks(timeOutRunnable);
    }

    @Override
    public void onCodeUnknow() {
        Log.e("HTML", "un know");
        mTextView.setText("Un know");
        mWebView.stopLoading();
        isFinishLoad = true;
        mLoginButton.setEnabled(true);
    }

    private final class MyWebViewClient extends WebViewClient {

        private boolean isGetCode;

        OnCodeGetListener mOnCodeGetListener;

        public void clearCode() {
            isGetCode = false;
        }

        public OnCodeGetListener getOnCodeGetListener() {
            return mOnCodeGetListener;
        }

        public void setOnCodeGetListener(OnCodeGetListener onCodeGetListener) {
            mOnCodeGetListener = onCodeGetListener;
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("HTML", "onPageStarted: ");
            super.onPageStarted(view, url, favicon);
        }

        public void onPageCommitVisible(WebView view, String url) {
            super.onPageCommitVisible(view, url);
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            Log.d("HTML", "start URL: " + url);
            if (url.endsWith("oauth.stu.edu.cn/cas")
                    || url.startsWith("https://oauth.stu.edu.cn/cas?ticket=")
                    || url.startsWith("http://oauth.stu.edu.cn/oauth2/authorize")) {

            } else if (url.equals("https://sso.stu.edu.cn/login?mobile=true&service=https%3A%2F%2Foauth.stu.edu.cn%2Fcas")) {
                String username = mUserNameEditText.getText().toString();
                String password = mPasswordEditText.getText().toString();

                view.loadUrl("javascript:document.getElementById(\"username\").value=\"" + username + "\";void(0);");
                view.loadUrl("javascript:document.getElementById(\"password\").value=\"" + password + "\";void(0);");
                view.loadUrl("javascript:document.getElementById('login').click();void(0);");
            } else if (url.equals("https://oauth.stu.edu.cn/oauth2/authorize?response_type=code&client_id=stusyllabus&redirect_uri=http://119.29.95.245:8080/oauth2_android")) {
                Log.d("HTML", "get token");
                view.loadUrl("javascript:document.getElementById('user_oauth_approval').click();void(0);");
            } else if (url.startsWith("https://sso.stu.edu.cn/login;jsessionid=")) {
                mOnCodeGetListener.onCodeFail();
//                view.loadUrl("javascript:window.local_obj.showSource('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
            } else if (url.startsWith("stu://syllabus:80/login?code=")) {
                String code = url.substring("stu://syllabus:80/login?code=".length(), url.length());
                Log.d("HTML", "code: " + code);
                if (!TextUtils.isEmpty(code)) {
                    if (!isGetCode) {
                        isGetCode = true;
                        if (mOnCodeGetListener != null) {
                            mOnCodeGetListener.onCodeGet(code);
                        }
                    }
                }
            } else if (url.startsWith("http://119.29.95.245:8080/oauth2_android?code=")) {
                String code = url.substring("http://119.29.95.245:8080/oauth2_android?code=".length(), url.length());
                Log.d("HTML", "code: " + code);
                if (!TextUtils.isEmpty(code)) {
                    if (!isGetCode) {
                        isGetCode = true;
                        if (mOnCodeGetListener != null) {
                            mOnCodeGetListener.onCodeGet(code);
                        }
                    }
                }
            } else {
                Log.d("HTML", "unknow URL: " + url);
                mOnCodeGetListener.onCodeUnknow();
            }
            super.onPageFinished(view, url);
        }
    }

    private final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void showSource(String html) {
            Log.d("HTML", html);
        }
    }

}
